<template>
  <div id="teamCardList">
    <van-card
        id="teamCards"
        v-for="team in props.teamList"
        :thumb="team.teamUrl"
        :desc="team.description"
        :title="`${team.name}`"
    >
      <template #tags>
        <van-tag plain type="danger" style="margin-right: 8px; margin-top: 8px">
          {{
            teamStatusEnum[team.status]
          }}
        </van-tag>
      </template>
      <template #bottom>
        <div>
          {{ `队伍人数：${team.hasJoinNum}/${team.maxNum}`}}
        </div>
        <div v-if="team.expireTime">
          {{ '过期时间：' + dateFormat(team.expireTime) }}
        </div>
<!--        <div>-->
<!--          {{ '创建时间：' + dateFormat(team.createTime) }}-->
<!--        </div>-->
      </template>
      <template #footer>
        <van-button v-if="team.userId !== currentUser?.id && !team.hasJoin" size="mini" plain type="primary" @click="preJoinTeam(team)">
          加入队伍</van-button>
        <van-button v-if="team.userId === currentUser?.id || currentUser?.userRole === 1" size="mini" plain type="primary" @click="doUpdateTeam(team.id)">
          更新队伍</van-button>
        <van-button v-if="team.userId !== currentUser?.id && team.hasJoin" size="mini" plain type="primary" @click="doQuitTeam(team.id)">
          退出队伍</van-button>
        <van-button v-if="team.userId === currentUser?.id || currentUser?.userRole === 1" size="mini" plain type="danger" @click="doDeleteTeam(team.id)">
          解散队伍</van-button>
        <van-button plain size="small"
                    @click="doTeamDetail(team.id)">查看队伍
        </van-button>
      </template>
    </van-card>

  </div>
  <van-dialog v-model:show="showPasswordDialog" title="请输入密码" show-cancel-button @confirm="doJoinTeam" @cancel="doJoinCancel">
    <van-field v-model="password" placeholder="请输入密码"/>
  </van-dialog>
</template>

<script setup lang="ts">
import {TeamType} from "../models/team";
import {useRouter} from "vue-router";
import myAxios from "../plugins/myAxios";
import {showFailToast, showSuccessToast} from "vant";
import {teamStatusEnum} from "../constants/team";
import {onMounted, ref} from "vue";
import {getCurrentUser} from "../services/user";
import dateFormat from "../plugins/dateFormat.ts";

interface TeamCardListProps{
  teamList: TeamType[];
}

const props= withDefaults(defineProps<TeamCardListProps>(),{
  //@ts-ignore
  teamList: [] as TeamType[]
});

const pageNum = ref(1);



/**
 * 格式化日期
 * @param time
 */
// const dateFormat = (time) => {
//   const date = new Date(time);
//   //获取年
//   const year = date.getFullYear();
//   //获取月 小于10前面加0
//   date.setMonth(date.getMonth() + 1);
//   let month = date.getMonth() < 10? '0' + date.getMonth() : date.getMonth();
//   //如果日期是0，就是12月
//   if (date.getMonth() === 0){
//     month = 12;
//   }
//   //获取日
//   const day = date.getDate() < 10? '0' + date.getDate() : date.getDate();
//   // const day = date.getDay().toString().length < 10? '0' + date.getDay().toString() : date.getDay().toString();
//   // console.log("y= " + year + ",m= "+ month + "，d= " + day)
//   //获取小时和分钟
//   const hours = date.getHours() < 10? '0' + date.getHours() : date.getHours();
//   const minutes = date.getMinutes() < 10? '0' + date.getMinutes() : date.getMinutes();
//   return `${year}-${month}-${day} ${hours}:${minutes}`
// }

const router = useRouter();

const joinTeamId = ref(0);
const password = ref('');
const showPasswordDialog = ref(false);


/**
 * 加入队伍
 */
const doJoinTeam = async () => {
  if (!joinTeamId.value){
    return;
  }
  const res = await myAxios.post("/team/join", {
    teamId: joinTeamId.value,
    password: password.value
  });
  if (res?.code === 0){
    showSuccessToast("加入成功");
    doJoinCancel();
  }else {
    doJoinCancel();
    showFailToast("加入失败" + (res.description ? `，${res.description}` : ''))
  }
}

/**
 * 判断是不是加密队伍，是就显示密码框
 * @param team
 */
const preJoinTeam = (team: TeamType) => {
  joinTeamId.value = team.id;
  if (team.status === 0){
    doJoinTeam()
  }else {
    showPasswordDialog.value = true;
  }
}

/**
 * 密码清空
 */
const doJoinCancel = () => {
  joinTeamId.value = 0;
  password.value = '';
}

/**
 * 退出队伍
 * @param id
 */
const doQuitTeam = async (id: number) => {
  const res = await myAxios.post('/team/quit', {
    teamId: id
  });
  if (res?.code === 0){
    showSuccessToast("操作成功");
  }else {
    showFailToast("操作失败" + (res.description ? `，${res.description}` : ''))
  }
}

/**
 * 解散队伍
 * @param id
 */
const doDeleteTeam = async (id: number) => {
  const res = await myAxios.post('/team/delete', {
    teamId: id
  });
  if (res?.code === 0){
    showSuccessToast("操作成功");
    //刷新页面

  }else {
    showFailToast("操作失败" + (res.description ? `，${res.description}` : ''))
  }
}

const refreshing = ref(false);
const loading = ref(false);
/**
 * 加载
 */
const onLoad = () => {

  setTimeout(() => {
    if (refreshing.value) {
      refreshing.value = false;
    }
    loading.value = false;
  }, 1000);
};

const currentUser = ref();
//调用获取当前用户方法
onMounted(async () => {
  currentUser.value = await getCurrentUser();
})

/**
 * 跳转到更新页面
 * @param id
 */
const doUpdateTeam = (id: number) => {
  router.push({
    path: '/team/update',
    query: {
      id,
    }
  })
}

/**
 * 跳转至队伍详情页
 * @param id
 */
const doTeamDetail = (id: number) => {
  router.push({
    path: '/team/detail',
    query: {
      id,
    }
  })
}

</script>

<style scoped>
#teamCardList :deep(.van-image_img){
  height: 128px;
  object-fit: unset;
}
#teamCardList{
  background-color: #f0f2f5;
}
#teamCards{
  background-color: white;
}
</style>